﻿@model ProductListModel
@using Telerik.Web.Mvc.UI
@{
	var allString = T("Admin.Common.All").Text;
    
    ViewBag.Title = T("Admin.Catalog.Products.Manage").Text;
}
@using (Html.BeginForm())
{
    <div class="section-header">
        <div class="title">
            <i class="fa fa-cube"></i>
            @T("Admin.Catalog.Products.Manage")
        </div>
        <div class="options">
			@{ Html.RenderWidget("admin_button_toolbar_before"); }

			<div class="input-group d-inline-flex mr-3" style="width: 350px">
				@Html.TextBoxFor(model => Model.GoDirectlyToSku, new { @class = "form-control", placeholder = T("Admin.Catalog.Products.List.GoDirectlyToSku") })
				<div class="input-group-append">
					<button type="submit" class="btn btn-secondary" id="go-to-product-by-sku" name="go-to-product-by-sku" value="go-to-product-by-sku" title="@T("Admin.Catalog.Products.List.GoDirectlyToSku.Hint")">
						<i class="fa fa-search"></i>
					</button>
					<button type="button" class="btn btn-outline-secondary btn-toggle-filter" data-toggle="button" aria-pressed="false">
						<i class="fa fa-filter"></i>
						<span>@T("Common.Filter")</span>
						<i class="fa fa-angle-double-down"></i>
					</button>
				</div>
			</div>		

            <a href="@Url.Action("Create")" class="btn btn-primary">
                <i class="fa fa-plus"></i>
				<span>@T("Admin.Common.AddNew")</span>
            </a>

			<button type="submit" id="delete-selected" class="btn btn-secondary btn-to-danger">
				<i class="far fa-trash-alt"></i>
				<span>@T("Admin.Common.Delete.Selected")</span>
			</button>

			@{ Html.RenderWidget("admin_button_toolbar_after"); }
        </div>
    </div>

	<div class="row mt-3 grid-filter" style="display: none">
		<div class="col-sm-6 col-lg-4 col-xl-3 form-group">
			@Html.SmartLabelFor(model => model.SearchProductName)
			@Html.TextBoxFor(model => Model.SearchProductName, new { @class = "form-control" })
		</div>
		<div class="col-sm-6 col-lg-4 col-xl-3 form-group">
			@Html.SmartLabelFor(model => model.SearchProductTypeId)
			@Html.DropDownListFor(model => model.SearchProductTypeId, Model.AvailableProductTypes, allString, new { @class = "form-control" })
		</div>
		<div class="col-sm-6 col-lg-4 col-xl-3 form-group">
			@Html.SmartLabelFor(model => model.SearchIsPublished)
			@Html.EditorFor(model => model.SearchIsPublished)
		</div>
		<div class="col-sm-6 col-lg-4 col-xl-3 form-group">
			@Html.SmartLabelFor(model => model.SearchHomePageProducts)
			@Html.EditorFor(model => model.SearchHomePageProducts)
		</div>
		<div class="col-sm-6 col-lg-4 col-xl-3 form-group">
			@Html.SmartLabelFor(model => model.SearchWithoutCategories)
			@Html.EditorFor(model => model.SearchWithoutCategories)
		</div>
		<div class="col-sm-6 col-lg-4 col-xl-3 form-group">
			@Html.SmartLabelFor(model => model.SearchCategoryId)
			@Html.DropDownListFor(model => model.SearchCategoryId, Model.AvailableCategories, allString, new { @class = "form-control" })
		</div>
		<div class="col-sm-6 col-lg-4 col-xl-3 form-group">
			@Html.SmartLabelFor(model => model.SearchWithoutManufacturers)
			@Html.EditorFor(model => model.SearchWithoutManufacturers)
		</div>
		<div class="col-sm-6 col-lg-4 col-xl-3 form-group">
			@Html.SmartLabelFor(model => model.SearchManufacturerId)
			@Html.DropDownListFor(model => model.SearchManufacturerId, Model.AvailableManufacturers, allString, new { @class = "form-control" })
		</div>
		@if (Model.AvailableStores.Count > 1)
		{
			<div class="col-sm-6 col-lg-4 col-xl-3 form-group">
				@Html.SmartLabelFor(model => model.SearchStoreId)
				@Html.DropDownListFor(model => model.SearchStoreId, Model.AvailableStores, allString, new { @class = "form-control" })
			</div>
		}
		<div class="col-sm-6 col-lg-4 col-xl-3 form-group ml-auto">
			@Html.SmartLabel(string.Empty, string.Empty)
			<button type="submit" id="search-products" value="search-products" class="btn btn-warning btn-block">
				<span>@T("Admin.Common.ApplyFilter")</span>
			</button>
		</div>
	</div>
	
	<div>
		@(Html.Telerik().Grid<ProductModel>()
			.Name("products-grid")
			.Columns(columns =>
			{
				columns.Bound(x => x.Id)
					.Filterable(false)
					.Sortable(false)
					.Template(x => string.Format("<input type='checkbox' name='checkedRecords' value='{0}' class='checkboxGroups'/>", x.Id))
					.ClientTemplate("<input type='checkbox' name='checkedRecords' value='<#= Id #>' class='checkboxGroups'/>")
					.Title("<input id='mastercheckbox' type='checkbox'/>")
					.Width(50)
					.HtmlAttributes(new { style = "text-align:center" })
					.HeaderHtmlAttributes(new { style = "text-align:center" });

				if (Model.DisplayProductPictures)
				{
					columns.Bound(x => x.PictureThumbnailUrl)
						.Sortable(false)
						.Width(50)
						.Template(
						@<text>
							<img alt="@item.Id" src="@item.PictureThumbnailUrl" @Html.Attr("class", "zoomable-thumb", !item.NoThumb) />
						</text>
						)
						.ClientTemplate("<div class='zoomable-thumb-container'><img alt='<#= Id #>' src='<#= PictureThumbnailUrl #>' <# if (!NoThumb) {#> class='zoomable-thumb' <# } #> /></div>");
				}
				columns.Bound(x => x.Name)
					.Template(x => @Html.LabeledProductName(x.Id, x.Name, x.ProductTypeName, x.ProductTypeLabelHint))
					.ClientTemplate(@Html.LabeledProductName("Id", "Name"));
				columns.Bound(x => x.Sku);
				columns.Bound(x => x.Price)
					.Format("{0:0.00}")
					.RightAlign();
				columns.Bound(x => x.StockQuantity)
					.Centered();
				columns.Bound(x => x.LimitedToStores)
					.Template(item => @Html.SymbolForBool(item.LimitedToStores))
					.ClientTemplate(@Html.SymbolForBool("LimitedToStores"))
					.Hidden(Model.AvailableStores.Count <= 1)
					.Centered();
				columns.Bound(x => x.CreatedOn);
				columns.Bound(x => x.UpdatedOn);
				columns.Bound(x => x.Published)
					.Template(item => @Html.SymbolForBool(item.Published))
					.ClientTemplate(@Html.SymbolForBool("Published"))
					.Centered();
			})
			.Sortable(x =>
			{
				x.AllowUnsort(true);
				x.SortMode(GridSortMode.SingleColumn);
			})
			.Pageable(settings => settings.PageSize(Model.GridPageSize).Position(GridPagerPosition.Both))
			.DataBinding(dataBinding => dataBinding.Ajax().Select("ProductList", "Product"))
			.ClientEvents(events => events.OnDataBinding("productsGrid_onDataBinding").OnDataBound("productsGrid_onDataBound"))
			.EnableCustomBinding(true)
			.PreserveGridState())
	</div>
    
    <script type="text/javascript">
		@*used by widget SmartStore.CommonExportProviders::ExportButtonsGeneral.cshtml*@
		var selectedIds = [];

		$(function () {

			$("#products-grid").thumbZoomer();

			// Filter toggler
			$('.btn-toggle-filter').on('click', function (e) {
				$('.grid-filter').slideToggle({ duration: 200, easing: 'ease-in-out' });
			});

			//search button
			$('#search-products').click(function () {
				//search
				var grid = $('#products-grid').data('tGrid');
				grid.currentPage = 1; //new search. Set page size to 1
				grid.ajaxRequest();
				//clear selected checkboxes
				$('.checkboxGroups').attr('checked', false).change();
				selectedIds = [];
				return false;
			});

			$("#@Html.FieldIdFor(model => model.SearchProductName)").keydown(function (event) {
				if (event.keyCode == 13) {
					$("#search-products").click();
					return false;
				}
			});

			$("#@Html.FieldIdFor(model => model.GoDirectlyToSku)").keydown(function (event) {
				if (event.keyCode == 13) {
					$("#go-to-product-by-sku").click();
					return false;
				}
			});

			// show/hide category filter
			$('#SearchWithoutCategories').on('change', function () {
				if (_.isEmpty($(this).val())) {
					$('#@Html.IdFor(x => x.SearchCategoryId)').removeAttr('disabled');
				}
				else {
					$('#@Html.IdFor(x => x.SearchCategoryId)').attr('disabled', 'disabled');
				}
			}).trigger('change');

			// show/hide manufacturer filter
			$('#SearchWithoutManufacturers').on('change', function () {
				if (_.isEmpty($(this).val())) {
					$('#@Html.IdFor(x => x.SearchManufacturerId)').removeAttr('disabled');
				}
				else {
					$('#@Html.IdFor(x => x.SearchManufacturerId)').attr('disabled', 'disabled');
				}
			}).trigger('change');

			$('#mastercheckbox').click(function () {
				$('.checkboxGroups').attr('checked', $(this).is(':checked')).change();
			});

			//"Delete (selected)" button
            $('#delete-selected').click(function (e) {
                if (confirm(@T("Admin.Common.AskToProceed").JsText)) {
                    e.preventDefault();
                    //redirect to required URL
                    setLocation('@(Url.Action("DeleteSelected", "Product"))?selectedIds=' + selectedIds.join(","));
                    return false;
                }
			});

			//wire up checkboxes.
			$(document).on('change', '#products-grid input[type=checkbox][id!=mastercheckbox]', function (e) {
				var $check = $(this);
				if ($check.is(":checked") == true) {
					var checked = jQuery.inArray($check.val(), selectedIds);
					if (checked == -1) {
						//add id to selectedIds.
						selectedIds.push($check.val());
					}
				}
				else {
					var checked = jQuery.inArray($check.val(), selectedIds);
					if (checked > -1) {
						//remove id from selectedIds.
						selectedIds = $.grep(selectedIds, function (item, index) {
							return item != $check.val();
						});
					}
				}
				productsGrid_updateMasterCheckbox();
			});
		});

		function productsGrid_onDataBinding(e) {
			var searchModel = {
				SearchProductName: $('#@Html.FieldIdFor(model => model.SearchProductName)').val(),
				SearchCategoryId: $('#SearchCategoryId').val(),
				SearchManufacturerId: $('#SearchManufacturerId').val(),
				SearchStoreId: $('#SearchStoreId').val(),
				SearchProductTypeId: $('#SearchProductTypeId').val(),
				SearchWithoutCategories: $('#SearchWithoutCategories').val(),
				SearchWithoutManufacturers: $('#SearchWithoutManufacturers').val(),
				SearchIsPublished: $('#SearchIsPublished').val(),
				SearchHomePageProducts: $('#SearchHomePageProducts').val()
			};
			e.data = searchModel;
		}

		function productsGrid_onDataBound(e) {
			$('#products-grid input[type=checkbox][id!=mastercheckbox]').each(function () {
				var currentId = $(this).val();
				var checked = jQuery.inArray(currentId, selectedIds);
				//set checked based on if current checkbox's value is in selectedIds.
				$(this).attr('checked', checked > -1);
			});

			productsGrid_updateMasterCheckbox();
		}

		function productsGrid_updateMasterCheckbox() {
			var numChkBoxes = $('#products-grid input[type=checkbox][id!=mastercheckbox]').length;
			var numChkBoxesChecked = $('#products-grid input[type=checkbox][checked][id!=mastercheckbox]').length;
			$('#mastercheckbox').attr('checked', numChkBoxes == numChkBoxesChecked && numChkBoxes > 0);
		}
    </script>  
}